package com.example.base.mvvm

import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.paging.*
import com.example.base.entity.Res
import com.example.base.net.ApiService
import com.google.gson.Gson
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.launch
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody

open class BaseViewModel : ViewModel() {

    /**
     * 网络请求
     * s:网络请求接口
     * success：响应成功时把结果回调出去
     */
    fun <T> httpRequest(s:suspend ()-> Res<T>, success:(T)->Unit){
        viewModelScope.launch(Dispatchers.IO) {
            try {
                val res = s.invoke()
                if(res.code == 200){
                    success(res.data)
                }else{
                    Log.i("yz", res.message)
                }
            }catch (e:Exception){
                Log.i("yz", e.message.toString())
            }
        }
    }


    fun toBody(item:Any):RequestBody{
        val toJson = Gson().toJson(item)
        val body = RequestBody.create("application/json".toMediaType(), toJson)
        return body
    }

}